/*
 DLGoogleLocalQuery.m
 Date Created: February 22, 2010
 
 Author: Karol Krizka <kkrizka@gmail.com>
 
 Copyright (C) 2010 Green-Power
 
 URL: http://code.google.com/p/green-power
 
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 $Id$
 */

#import "DLGoogleLocalQuery.h"

#import "../json-framework/SBJSON.h"
#import "DLRecyclingDepot.h"

@implementation DLGoogleLocalQuery

@synthesize queryName;
@synthesize delegate;

- (id)initWithQuery:(NSString *)newQueryName {
  self=[super init];
  if( self ) {
    queryName=newQueryName;
    datas=[[NSMutableArray arrayWithCapacity:5] retain];
    connections=[[NSMutableArray arrayWithCapacity:5] retain];
    asyncLock=[[NSLock alloc] init];
  }
  return self;
}

- (void)lookUpAtLocation:(CLLocationCoordinate2D)coordinate {
  NSString *googleURL=[[NSString alloc] initWithFormat:@"http://www.ajax.googleapis.com/ajax/services/search/local?q=%@&v=1.0&sll=%f,%f&rsz=large",queryName,coordinate.latitude,coordinate.longitude];
  NSString *encodedGoogleURL=[googleURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
	NSURLRequest* request=[NSURLRequest requestWithURL:[NSURL URLWithString:encodedGoogleURL]];

  if(!request) {
    // TODO Handle error
    NSLog(@"Problem setting up request");
    return;
  }

  [asyncLock lock];
  NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];

  NSMutableData *data=[NSMutableData data];
  [datas addObject:data];
  [connections addObject:connection];
  [asyncLock unlock];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)newdata {
  [asyncLock lock];
  NSUInteger index=[connections indexOfObject:connection];
  NSMutableData *data=[datas objectAtIndex:index];

  [data appendData:newdata];
  [asyncLock unlock];  
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  [asyncLock lock];
  NSUInteger index=[connections indexOfObject:connection];
  NSMutableData *data=[datas objectAtIndex:index];
  
  NSString* json_string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  [self parseResults:json_string];
  
  [datas removeObjectAtIndex:index];
  [connections removeObjectAtIndex:index];
  [asyncLock unlock];
}

- (void)parseResults:(NSString *)resultsString {
  // Initialize parser
	SBJSON* parser=[[SBJSON alloc] init];
  NSError *error;
	NSDictionary* parsed=[parser objectWithString:resultsString error:&error];
  if( !parsed ) {
    NSLog(@"Error parsing Google Local results: %@",error);
    [delegate googleLocalQuery:self finishedWithParseError:error];
    return;
  }
  
  NSUInteger responseStatus=[[parsed objectForKey:@"responseStatus"] intValue];
  
  NSMutableArray *listOfDepots;
  if( responseStatus == 200 ) { // Correct response, find data..
    NSDictionary* results=[[parsed objectForKey:@"responseData"] objectForKey:@"results"];
	
    listOfDepots=[NSMutableArray arrayWithCapacity:[results count]];
    
    // Loop over all the results
    for(NSDictionary* result in results)
    {
      NSString* latStr = [result valueForKey:@"lat"];
      float lat = [latStr floatValue];
      NSString* lngStr = [result valueForKey:@"lng"];
      float lng = [lngStr floatValue];
		
		
      NSString* name=[[NSString alloc] initWithString:[result valueForKey:@"titleNoFormatting"]];
      NSString* address=[[NSString alloc] initWithFormat:@"%@, %@",[result valueForKey:@"streetAddress"],[result valueForKey:@"city"]];
      
      DLRecyclingDepot *depot=[[DLRecyclingDepot alloc] init];
      depot.name=name;
      depot.address=address;
      
      CLLocationCoordinate2D coordinate;
      coordinate.latitude=lat;
      coordinate.longitude=lng;
      depot.coordinate=coordinate;
      
      
      [listOfDepots addObject:depot];
    }
  }

  [delegate googleLocalQuery:self finishedWithStatus:responseStatus results:[NSArray arrayWithArray:listOfDepots]];
}

- (void)dealloc {
  [asyncLock release];
  [datas release];
  [connections release];
  
  [super dealloc];
}

@end
